/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.vng.zing.survey.memcached.SurveyCache;
import com.vng.zing.survey.thrift.client.SurveyClient;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import com.vng.zing.survey.thrift.model.UserType;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxDeleteSurvey extends BaseController {

    private static UserType userType = UserType.ADMIN;

    @Override
    public String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception {
        try {
            if (request.getParameter("idSurvey") == null) {
                return CommonModel.toJSON("ERROR", "Tham số không hợp lệ!");
            }
            int idSurvey = Integer.parseInt(request.getParameter("idSurvey"));
            Map map = checkMember(request, userType);
            if (map.containsValue(ErrorType.FAIL) || map.containsValue(ErrorType.ERROR_SYSTEM)) {
                return CommonModel.toJSON("ERROR", (String) map.get("msg"));
            }
            int idUser = (int) map.get("msg");
            SurveyItemResult surveyItemResult = SurveyClient.getInstance().getSurvey(idSurvey);
            if (idUser != surveyItemResult.getSurveyItem().getIDUser()) {
                return CommonModel.toJSON("ERROR", "Bạn không phải là admin!");
            }
            Error error = SurveyCache.removeSurveyWithCache(idSurvey, idUser);
            return CommonModel.toJSON(error, "");
        } catch (Exception ex) {
             Logger.getLogger(this.getName()).error(ex.toString());
            return CommonModel.toJSON("ERROR", "");
        }

    }
}
